package com.edwin.websitebe.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;

import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

public class TokenUtil {

    private static final String KEY = "bfd98ffz9f8e98g8";

    public static String createToken(Long userId) {
        HashMap<String, Object> map = new HashMap<>(1);
        map.put("userId", userId);
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        return JWT.create()
                .setPayload("userId", userId)
                .setKey(KEY.getBytes(StandardCharsets.UTF_8))
                .setExpiresAt(calendar.getTime())
                .sign();
    }

    public static boolean verify(String token) {
        boolean verifyKey = JWTUtil.verify(token, KEY.getBytes(StandardCharsets.UTF_8));
        if (!verifyKey) {
            return false;
        }
        try {
            JWTValidator.of(token).validateDate(DateUtil.date());
            return true;
        } catch (ValidateException e) {
            return false;
        }
    }

    public static Long getUserId(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        return Long.valueOf(String.valueOf(jwt.getPayload("userId")));
    }

}
